package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.*;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author suiweihua
 * @version 1.0
 * @description: TODO 员工管理-控制器
 * @date 2022/6/5 15:30
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 功能描述 :分页查询员工
     *
     * @param page
     * @param pageSize
     * @param name
     * @return : com.itheima.common.PageResult
     */
    @GetMapping("/page")
    public PageResult pageResult(@RequestParam("page") Integer page,
                                 @RequestParam("pageSize") Integer pageSize,
                                 @RequestParam(value = "name", required = false) String name) {
        Page<Employee> pageResult = employeeService.page(page, pageSize, name);
        List<Employee> records = pageResult.getRecords();
        long total = pageResult.getTotal();
        return new PageResult(Code.OK, MessageConstant.EMP_SEARCH_SUCCESS, records, total);
    }

    /**
     * 功能描述 :新增员工
     *
     * @param employee
     * @return : com.itheima.common.Result
     */
    @PostMapping
    public Result saveEmployee(@RequestBody Employee employee) {
        Result result = employeeService.saveEmployee(employee);
        if (result.getCode() != null) {
            return result;
        }
        int row = (int) result.getData();
        if (row < 1) {
            return new Result(Code.ERROR, MessageConstant.EMP_SAVE_ERROR);
        } else {
            return new Result(Code.OK, MessageConstant.EMP_SAVE_SUCCESS);
        }
    }

    /***
     * 功能描述: 员工登录
     * @param employee
     * @param request
     * @param response
     * @return : com.itheima.common.Result
     */
    @PostMapping("/login")
    public Result login(@RequestBody Employee employee, HttpServletRequest request, HttpServletResponse response) {
        //1.调用service业务处理结果
        Employee loginEmployee = employeeService.login(employee);
        //2.登录失败，返回前端友好错误提示
        if (loginEmployee == null) {
            return new Result(Code.ERROR, MessageConstant.LOGIN_ERROR);
        }
        //3.登录成功，把用户信息存入session；并且返回令牌（empToken）给前端浏览器
        //session中key的命名规范：业务主键_唯一主键
        String empToken = EmployeeConstant.EMPLOYEE_LOGIN + loginEmployee.getId();
        //新增内容：往cookie中添加令牌
        Cookie cookie = new Cookie(EmployeeConstant.TOKEN, empToken);
        cookie.setMaxAge(EmployeeConstant.TOKEN_EXPIRE);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        response.addCookie(cookie);
        request.getSession().setAttribute(empToken, loginEmployee.getId());
        //把用户名称作为数据返回，完成用户名称回显功能，不要把敏感信息传给前端dsa
        String username = loginEmployee.getUsername();
        return new Result(Code.OK, MessageConstant.LOGIN_SUCCESS, username);
    }
    /**
     * 功能描述 :编辑id回显
     *
     * @param id
     * @return : com.itheima.common.Result
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Long id) {
        Employee employee = employeeService.findById(id);
        if (employee == null) {
            return new Result(Code.ERROR, MessageConstant.EMP_GET_ERROR);
        }
        return new Result(Code.OK, MessageConstant.EMP_GET_SUCCESS, employee);
    }

    /**
     * 功能描述 :修改员工
     *
     * @param employee
     * @return : com.itheima.common.Result
     */
    @PutMapping
    public Result update(@RequestBody Employee employee) {
        Result result = employeeService.update(employee);
        if (result.getCode() != null) {
            return result;
        }
        int row = (int) result.getData();
        if (row < 1) {
            return new Result(Code.ERROR, MessageConstant.EMP_UPDATE_ERROR);
        } else {
            return new Result(Code.OK, MessageConstant.EMP_UPDATE_SUCCESS);
        }
    }

    /**
     * 功能描述 :修改员工状态
     *
     * @param employee
     * @return : com.itheima.common.Result
     */
    @PutMapping("/status")
    public Result updateStatus(@RequestBody Employee employee) {
        int row = employeeService.updateStatus(employee);
        if (row < 1) {
            return new Result(Code.ERROR, MessageConstant.EMP_UPDATE_STATUS_ERROR);
        }
        return new Result(Code.OK, MessageConstant.EMP_UPDATE_STATUS_SUCCESS);
    }

    /**
     * 功能描述 :批量删除员工
     *
     * @param ids
     * @return : com.itheima.common.Result
     */
    @DeleteMapping
    public Result delete(@RequestParam("ids") Long[] ids) {
        int row = employeeService.delete(ids);
        if (row < 1) {
            return new Result(Code.ERROR, MessageConstant.EMP_DELETE_ERROR);
        }
        return new Result(Code.OK, MessageConstant.EMP_DELETE_SUCCESS);
    }
    /**
     * 功能描述: 登出功能
     * @param session
     * @param response
     * @return : com.itheima.common.Result
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request , HttpSession session, HttpServletResponse response){
        //1.获取要删除的session的key（sessionId）
        String sId = null;
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            return new Result(Code.ERROR,MessageConstant.LOGOUT_ERROR);
        }
        for (Cookie cookie : cookies) {
            if(EmployeeConstant.TOKEN.equals(cookie.getName())){
                sId = cookie.getValue();
            }
        }
        //2.从session中删除指定的数据
        session.removeAttribute(sId);
        //redisTemplate.delete(sId);
        //3.从cookie删除指定的数据
        Cookie cookie = new Cookie("userInfo","");
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(EmployeeConstant.TOKEN_DEAD);//令牌失效
        response.addCookie(cookie);
        return new Result(Code.OK,MessageConstant.LOGOUT_SUCCESS);
    }
}
